/**
 * 添加问题
 */
import query from '../../untils/mysql';
import * as uuid from 'uuid';
import { Tip } from '../../untils/untils';
import { check, validationResult } from 'express-validator';
import mydayjs from '../../untils/day';

const validator = [
    check('type').notEmpty().withMessage("问题类型不能为空！").isIn(['1', '2', '3', '4']).withMessage("type取值有误"),
    check('projectId').notEmpty().withMessage("项目Id不能为空"),
    check('title').notEmpty().withMessage("问题标题不能为空！"),
    check('level').notEmpty().withMessage("优先级不能为空！").isIn(['1', '2', '3', '4']).withMessage("level取值有误"),
    check('serious').notEmpty().withMessage("严重等级不能为空！").isIn(['1', '2', '3']).withMessage("serious取值有误"),
    check('handlerId').notEmpty().withMessage("处理人不能为空！"),
    check('status').notEmpty().withMessage("状态不能为空！").isIn(['1', '2']).withMessage("serious取值有误")
]
const POST = async (req: any, res: any, next: any) => {
    try {
        const { type, projectId, title, remakes, startTime, endTime, level, serious, handlerId, sendId, fileId, status } = req.body;
        const { userId } = req.auth;
        var errors = validationResult(req);
        if (!errors.isEmpty()) {
            return Tip.tipError(res, errors.array()[0].msg);
        }
        let _projectId = await query(`select id from project where id = '${projectId}'`);
        if (_projectId.length === 0) {
            return Tip.tipError(res, '项目id不存在')
        };

        let _handlerId = await query(`select id from user where id = '${handlerId}'`);
        if (_handlerId.length === 0) {
            return Tip.tipError(res, '处理人id不存在')
        };

        if (sendId) {
            let _sendId = await query(`select id from user where id = '${sendId}'`);
            if (_sendId.length === 0) {
                return Tip.tipError(res, '处理人id不存在')
            }
        }

        const sql = `insert into problem (id, user_id,type, project_id, title, remakes,startTime,endTime, level, serious, handlerId, sendId, fileId, status,actionStatus,actionTime) values `
            + `('${uuid.v1()}','${userId}','${type}','${projectId}', '${title}', '${remakes}','${startTime}','${endTime}', '${level}', '${serious}', '${handlerId}', '${sendId}', '${fileId}', '${status}','1','${mydayjs(new Date())}')`
        await query(sql)
        return Tip.tipSuccess(res, '新增成功')
    } catch (error: any) {
        Tip.tipError500(res, error)
    }
}

export {
    POST,
    validator
}